package com.tronsis.library.adapter.listview;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;


import java.util.List;

/**
 * 通用ListView Adapter
 *
 * @author allen@tronsis.com
 * @date 2016-1-18 上午9:57:54
 */
public abstract class CommonListAdapter<T> extends BaseAdapter implements SectionIndexer {
    protected LayoutInflater inflater;
    protected Context context;
    protected List<T> data;
    protected final int itemLayoutId;

    public CommonListAdapter(Context context, List<T> data, int itemLayoutId) {
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.data = data;
        this.itemLayoutId = itemLayoutId;
    }

    public void notifyDataSetChanged(List<T> data) {
        this.data = data;
        this.notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    public T getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder = getViewHolder(position, convertView, parent);
        convert(viewHolder, getItem(position), position);
        return viewHolder.getConvertView();
    }

    public abstract void convert(ViewHolder helper, T item, int position);

    private ViewHolder getViewHolder(int position, View convertView, ViewGroup parent) {
        return ViewHolder.get(context, convertView, parent, itemLayoutId, position);
    }


    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    @Override
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            /*SortModel sortModel = (SortModel) data.get(i);
            String sortStr = sortModel.getPinyinCategory();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == section) {
                return i;
            }*/
        }

        return -1;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    @Override
    public int getSectionForPosition(int position) {
       /* SortModel sortModel = (SortModel) data.get(position);
        return sortModel.getPinyinCategory().charAt(0);*/
        return -1;
    }

    @Override
    public Object[] getSections() {
        return null;
    }

}
